//  this library.
import 'dart:async';

import 'package:flutter/material.dart';
import 'package:hktk_app/util/font_util.dart';
import 'package:hktk_app/util/view_util.dart';

/// 考试倒计时显示组件
class ExamCountDownWidget extends StatefulWidget {
  /// 倒计时时间
  final Duration duration;

  /// 倒计时结束方法
  final Function() endFun;

  const ExamCountDownWidget({
    super.key,
    required this.duration,
    required this.endFun,
  });

  @override
  State<ExamCountDownWidget> createState() => _ExamCountDownWidgetState();
}

class _ExamCountDownWidgetState extends State<ExamCountDownWidget> {
  /// 倒计时工具类
  late Timer _timer;

  /// 显示字符串
  late String _showText;

  @override
  void initState() {
    super.initState();
    debugPrint("examCountDownWidget 组件 -> initState 方法执行 ===> ");
    debugPrint("");
    _showText = _showTime(widget.duration.inSeconds);
    _startCountDown();
  }

  @override
  void dispose() {
    super.dispose();
    debugPrint("examCountDownWidget 组件 -> dispose 方法执行 ===> ");
    debugPrint("");
    if (_timer.isActive) {
      _timer.cancel();
    }
  }

  @override
  Widget build(BuildContext context) {
    // debugPrint("examCountDownWidget 组件 -> build 方法执行 ===> ");
    // debugPrint("");
    return Text(
      _showText,
      style: FontUtil.fontBlue1(28),
    );
  }

  /// 开始倒计时方法
  void _startCountDown() {
    int total = widget.duration.inSeconds;
    // 循环执行，间隔一秒
    _timer = Timer.periodic(const Duration(seconds: 1), (timer) {
      total--;
      if (total < 1) {
        _timer.cancel();
        widget.endFun();
      }
      // 计算倒计时
      _showText = _showTime(total);
      setState(() {});
      // timer.cancel();
    });
  }

  /// 格式化时间显示
  String _getTimeStr(int num) {
    return num < 10 ? "0$num" : num.toString();
  }

  /// 计算显示的时间
  String _showTime(int total) {
    int minute = total ~/ 60;
    int seconds = total % 60;
    return "${_getTimeStr(minute)} : ${_getTimeStr(seconds)}";
  }
}
